﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LDSP.Helper;
using LDSP.BRL;
using BYFW.DAL;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using System.Web.UI.HtmlControls;

namespace LDSP.UI.EnterpriseAdmin.Report
{
    public partial class TaskStatusReport : LDSP.BRL.BaseEnterpriseAdminPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.RB())
                {
                    this.InitDataDynamicBefore();
                    if (!IsPostBack)
                    {
                        this.InitData();
                    }
                }
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }

        public override void RedirectBefore()
        {
            if (LoginUser == null)
            {
                //this.GoToLogin();
            }
        }

        /// <summary>
        /// 传入参数，设置过滤条件
        /// </summary>
        protected void SetSpecialPageInfo()
        {
        }
        protected bool RB()
        {
            return true;
        }
        protected void InitData()
        {
            //不缓存则清空页面信息
            if (!needCachePageInfo)
            {
                g_pageInfo.ClearPageInfo();
            }
            this.SetSpecialPageInfo();

            if (IsEnterpriseGroupAdmin)
            {
                BindDDLSubdiary();
            }

            this.SetStatus();

            CreateReport();
        }

        private void SetStatus()
        {
            this.tr_subdiary.Visible = IsEnterpriseGroupAdmin;
        }
        protected void InitDataDynamicBefore()
        {
        }
        protected void BindDDLSubdiary()
        {
            CommonControlInitial.InitialSubdiary(this.ddl_subdiary, this.LoginUser.Enterprise.GetSubsidiaryList());
        }

        protected void GetCondition()
        {
            string cond = "";
            if (this.txt_implementStartDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.implementDT", EDataType.Date, this.txt_implementStartDT.Text, ">=", false), true);
            }
            if (this.txt_implementEndDT.Text.Trim() != "")
            {
                cond = this.AppendCondition(cond, DefaultDB.GetSQLNormalCondition("t.implementDT", EDataType.Date, this.txt_implementEndDT.Text, "<=", false), true);
            }
            if (cond.Trim() != "")
            {
                cond = "and " + cond;
            }
            g_pageInfo.Condition = cond;
        }

        protected void CreateReport()
        {
            if (!IsEnterpriseGroupAdmin)
            {//非集团公司
                this.CreateTaskStatusReport(this.cht_taskStatus, this.LoginUser.EnterpriseID);
            }
            else if (IsEnterpriseGroupAdmin && this.ddl_subdiary.SelectedValue != "0")
            {//选择指定的子公司
                this.CreateTaskStatusReport(this.cht_taskStatus, Int32.Parse(this.ddl_subdiary.SelectedValue));
            }
            else
            {//整个集团
                this.CreateEGTaskStatusReport(this.cht_taskStatus, this.LoginUser.EnterpriseID);
            }

            this.CreateFavoriteStatusReport(this.cht_favoriteStatus, this.LoginUser.EnterpriseID);
        }
        private void CreateEGTaskStatusReport(Chart chart, int enterpriseId)
        {
            DataTable dt = new Plan().GetEGReportForStatus(enterpriseId, g_pageInfo.Condition);

            GenerateColumnChart(chart, dt, "计划任务状态分布图", new string[] { "进行中", "已完成", "暂停" });
        }
        protected void CreateTaskStatusReport(Chart chart, int enterpriseId)
        {
            var etts = new Plan().GetReportForStatus(enterpriseId, g_pageInfo.Condition);
            int finished = 0;
            int paused = 0;
            int inProgress = 0;
            foreach (var ett in etts)
            {
                switch (ett.Status)
                {
                    case (int)TaskStatus.已完成:
                        finished++;
                        break;
                    case (int)TaskStatus.暂停:
                        paused++;
                        break;
                    case (int)TaskStatus.进行中:
                        inProgress++;
                        break;
                }
            }
            UIHelper.SetCommonChart(chart, "计划任务状态分布图");

            double[] yValues = { finished, paused, inProgress };
            string[] xValues = { "已完成", "暂停", "进行中" };
            chart.Series[0].Points.DataBindXY(xValues, yValues);
            chart.Series[0].Points[0].Color = System.Drawing.Color.Green;
            for (int i = 0; i < xValues.Length; i++)
            {
                chart.Series[0].Points[i].Label = xValues[i] + ":" + yValues[i] + "个";
            }
        }
        protected void CreateFavoriteStatusReport(Chart chart, int enterpriseId)
        {
            DataTable dt = null;
            if (!IsEnterpriseGroupAdmin)
            {//非集团公司
                dt = new EnterpriseUser().GetEnterpriseReportUserPlan(enterpriseId, g_pageInfo.Condition);
            }
            else if (IsEnterpriseGroupAdmin && this.ddl_subdiary.SelectedValue != "0")
            {//选择指定的子公司
                dt = new EnterpriseUser().GetEnterpriseReportUserPlan(Int32.Parse(this.ddl_subdiary.SelectedValue), g_pageInfo.Condition);
            }
            else
            {//整个集团
                dt = new EnterpriseUser().GetEnterpriseGroupReportUserPlan(enterpriseId, g_pageInfo.Condition);
            }

            GenerateColumnChart(chart, dt, "各优先级法规标准的任务计划分布图", new string[] { "低", "中", "高" });
        }
        private void GenerateColumnChart(Chart chart, DataTable dt, string title, params string[] titles)
        {
            Dictionary<string, int[]> items = new Dictionary<string, int[]>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string n = dt.Rows[i]["name"].ToString();
                if (!items.ContainsKey(n))
                {
                    int[] t = new int[4];
                    items.Add(n, t);
                }
                int[] v = items[n];
                int p = this.GetInt(dt.Rows[i]["priority"]);
                int q = this.GetInt(dt.Rows[i]["number"]);
                v[p] = q;
            }

            chart.Series.Add("S2");
            chart.Series.Add("S3");
            UIHelper.SetCommonChart(chart, title, SeriesChartType.StackedColumn);

            chart.Series[0].LegendText = titles[0];
            chart.Series[1].LegendText = titles[1];
            chart.Series[2].LegendText = titles[2];

            int index = 0;
            int max = 0;
            foreach (var item in items)
            {
                chart.Series[0].Points.AddY(item.Value[0]);//已完成
                chart.Series[1].Points.AddY(item.Value[1]);//进行中
                chart.Series[2].Points.AddY(item.Value[3]);//未开始
                chart.Series[0].Points[index].AxisLabel = item.Key;
                index++;
                max = Math.Max(max, item.Value[0] + item.Value[1] + item.Value[3]);
            }

            if (items.Count > 5)
            {
                chart.Width = new Unit(chart.Height.Value + (items.Count - 5) * 20);
            }
            if (max > 7)
            {
                int maxHeight = 15;
                int offset = Math.Min(max, maxHeight);
                chart.Height = new Unit(chart.Height.Value + offset * 30);
                if (max > maxHeight)
                {
                    chart.ChartAreas[0].AxisX.Interval = 0;
                }

                chart.ChartAreas[0].AxisX.LabelStyle.Angle = -45;
            }
        }

        protected void btn_search_Click(object sender, EventArgs e)
        {
            try
            {
                this.GetCondition();
                this.CreateReport();
            }
            catch (Exception ex)
            {
                this.HandlerException(ex);
            }
        }
    }

}